package com.nw.serviceImpl;

import com.nw.service.ImageCodeService;
import com.nw.util.ImageCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Service
@Transactional
public class ImageCodeServiceImpl implements ImageCodeService {


    @Resource
    HttpServletResponse response;
    @Autowired
    RedisTemplate redisTemplate;
    @Resource
    StringRedisTemplate stringRedisTemplate;



    @Override
    public void getImageCode() {
        //获取验证码随机字符
        String imageCode = ImageCodeUtil.getSecurityCode();
        System.out.println("随机验证码为:" + imageCode);

        //准备验证码进入redis 结构 KEY ,（key，values）
        //解决乱码
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        //字符串拼接
        StringBuilder stringBuilder = new StringBuilder();
        //获取String类型的操作
        HashOperations hashOperations = stringRedisTemplate.opsForHash();
        //KEY采用统一的enCode字符串，key采用时间戳，value采用验证码
        hashOperations.put("enCode", imageCode, imageCode);

        BufferedImage image = ImageCodeUtil.createImage(imageCode);
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image,"png",outputStream);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("验证码输出错误");
        }
    }
}
